package com.uinnova.product.eam.base.util;

import com.binary.core.exception.BinaryException;
import com.binary.core.exception.MessageException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * excel工具类
 * @author ch
 */
@Slf4j
@Component
public class ExcelUtil {

    public static ResponseEntity<byte[]> returnRes(File file) {
        HttpHeaders headers = new HttpHeaders();
        InputStream inputStream = null;
        try {
            inputStream = Files.newInputStream(file.toPath());
            byte[] bytes = new byte[inputStream.available()];
            int read = inputStream.read(bytes);
            headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            throw new MessageException(e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                }
            }
        }
    }

    /**
     * 获取单元格样式
     * @param workbook 工作簿
     * @return 样式
     */
    public static CellStyle getCellStyle(Workbook workbook) {
        // 创建一个单元格样式，并设置合并单元格属性
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return cellStyle;
    }

    /**
     * 创建单元格
     * @param row 行
     * @param cellStyle 样式
     * @param value 单元格值
     * @param i 第几列
     * @return 单元格
     */
    public static Cell createCell(Row row, CellStyle cellStyle, String value, int i){
        Cell cell = row.createCell(i);
        if(cellStyle != null){
            cell.setCellStyle(cellStyle);
        }
        cell.setCellValue(value);
        return cell;
    }

    /**
     * 获取标题行样式
     * @param workbook 工作簿
     * @return 样式
     */
    public static CellStyle getTitleStyle(Workbook workbook) {
        // 创建一个单元格样式，并设置合并单元格属性
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 14);
        font.setBold(true);
        cellStyle.setFont(font);
        return cellStyle;
    }

    /**
     * 获取表头行样式
     * @param workbook 工作簿
     * @return 样式
     */
    public static CellStyle getHeaderStyle(Workbook workbook) {
        // 创建一个单元格样式，并设置合并单元格属性
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = workbook.createFont();
        font.setBold(true);
        cellStyle.setFont(font);
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return cellStyle;
    }

    /**
     * 获取一般行样式
     * @param workbook 工作簿
     * @return 样式
     */
    public static CellStyle getSimpleStyle(Workbook workbook) {
        // 创建一个单元格样式，并设置合并单元格属性
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setWrapText(true);
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        return cellStyle;
    }

    /**
     * 写出excel
     * @param workbook 工作簿
     * @param fileName 文件名
     * @return 写出文件
     */
    public static File writeExcel(Workbook workbook, String fileName){
        try {
            String path = URLDecoder.decode(ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath(), "utf-8");
            File exportDir = new File(path + "/static/download");
            if (!exportDir.exists()) {
                boolean mkdir = exportDir.mkdirs();
            }
            File file = new File(exportDir, fileName);
            // 将工作簿写入到文件中
            FileOutputStream outputStream = new FileOutputStream(file);
            workbook.write(outputStream);
            return file;
        } catch (Exception e) {
            log.error("生成矩阵excel失败:{}", e.getMessage());
            throw new BinaryException(e.getMessage());
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }

}
